package uhttp

import (
	"net/http"
	"encoding/json"
)

/**
 一些通用的错误码
 */
const (
	RespCodeOk = 1000

	RespCodeParamsErr = 1002                 // params error
	RespCodeReqBodyErr = 1003               // body error
	RespCodeJsonErr = 1004                   // json error
	RespCodeParamErr = 1005                  // param error
	RespCodeTokenErr = 1006                  // token verify

	RespCodeTooFast = 1007

	RespCodeAuthRedirect = 1008
	RespCodeAuthErr = 1009                  // auth fail

	RespCodeSystemErr = 1010                 // system error

	RespCodeAgentOffline = 1011           // wolagent不在线
)

/**
 基于map实现的基础的response data
 */
func CreateOkResponse(data interface{}) map[string]interface{} {
	respData := map[string]interface{}{"code": RespCodeOk, "msg": "ok", "data": data}
	return respData
}

func CreateErrResponse(code int, msg string, data interface{}) map[string]interface{} {
	respData := map[string]interface{}{"code": code, "msg": msg, "data": data}
	return respData
}

/**
 基于类ResponData执行的response操作
 */
type ResponData struct {
	Code            int         `json:"code"`
	Msg             string      `json:"msg"`
	Data            interface{} `json:"data"`
}

/**
 对于结果的解析中，采用mapstructure模块进行解析该模块
 todo：mapstructure模块需要做一个定制处理，待完成
 */
func (data ResponData)SendResponse(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json")

	buf, err := json.Marshal(data)
	if err != nil {
		tmpData := ResponData{Code: RespCodeSystemErr, Msg: "ResponData Marshal Error"}
		buf, _ := json.Marshal(tmpData)
		w.Write(buf)

		return err
	}

	w.Write(buf)
	return nil
}